<template>
  <div class="admin-layout">
    <!-- 移动端菜单按钮 -->
    <button
      class="mobile-menu-btn hidden-desktop"
      @click="toggleMobileSidebar"
      style="display: none;"
    >
      <el-icon><Menu /></el-icon>
    </button>

    <!-- 移动端遮罩层 -->
    <div
      v-if="mobileSidebarOpen"
      class="mobile-overlay"
      @click="closeMobileSidebar"
    ></div>

    <el-container>
      <el-aside :width="sidebarWidth" :class="{ 'mobile-open': mobileSidebarOpen }">
        <div class="logo-container">
          <el-icon class="logo-icon" :size="24"><Shop /></el-icon>
          <h1 class="title" v-show="!isCollapsed">管理后台</h1>
        </div>
        <el-menu
          router
          :default-active="$route.path"
          class="el-menu-vertical"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          :collapse-transition="false"
          :unique-opened="true"
          :collapse="isCollapsed"
          @select="handleMenuSelect"
        >
          <el-menu-item index="/admin/dashboard">
            <el-icon><Monitor /></el-icon>
            <span>概览</span>
          </el-menu-item>
          
          <!-- 收银员功能 -->
          <template v-if="hasPermission(['cashier', 'manager', 'admin'])">
            <div class="menu-title">收银功能</div>
            <el-menu-item index="/admin/orders">
              <el-icon><Document /></el-icon>
              <span>订单查询</span>
            </el-menu-item>
          </template>
          
          <!-- 商品管理 - 经理和管理员可见 -->
          <template v-if="hasPermission(['manager', 'admin'])">
            <div class="menu-title">商品管理</div>
            <el-menu-item index="/admin/products">
              <el-icon><Goods /></el-icon>
              <span>商品列表</span>
            </el-menu-item>
            <el-menu-item index="/admin/categories">
              <el-icon><Folder /></el-icon>
              <span>分类管理</span>
            </el-menu-item>
            <el-menu-item index="/admin/channels">
              <el-icon><Share /></el-icon>
              <span>渠道管理</span>
            </el-menu-item>
            <el-menu-item index="/admin/price-tools">
              <el-icon><PriceTag /></el-icon>
              <span>价格管理工具</span>
            </el-menu-item>
          </template>
          
          <!-- 用户与权限 - 仅管理员可见 -->
          <template v-if="hasPermission(['admin'])">
            <div class="menu-title">用户与权限</div>
            <el-menu-item index="/admin/users">
              <el-icon><User /></el-icon>
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="/admin/departments">
              <el-icon><OfficeBuilding /></el-icon>
              <span>部门管理</span>
            </el-menu-item>
            <el-menu-item index="/admin/roles">
              <el-icon><Connection /></el-icon>
              <span>角色管理</span>
            </el-menu-item>
          </template>
          
          <!-- 营销与数据 - 经理和管理员可见 -->
          <template v-if="hasPermission(['manager', 'admin'])">
            <div class="menu-title">营销与数据</div>
            <el-menu-item index="/admin/promotions">
              <el-icon><Discount /></el-icon>
              <span>促销管理</span>
            </el-menu-item>
            <el-menu-item index="/admin/reports">
              <el-icon><DataAnalysis /></el-icon>
              <span>报表中心</span>
            </el-menu-item>
          </template>
          
          <!-- 库存管理 - 经理、管理员和库存管理员可见 -->
          <!-- 临时禁用库存功能 -->
          <!--
          <template v-if="hasPermission(['manager', 'admin', 'inventory_manager'])">
            <div class="menu-title">库存管理</div>
            <el-sub-menu index="/admin/inventory" v-permission="'inventory.view'">
              <template #title>
                <el-icon><Goods /></el-icon>
                <span>库存管理</span>
              </template>
              <el-menu-item index="/admin/inventory/overview" v-permission="'inventory.view'">
                <el-icon><DataAnalysis /></el-icon>
                <span>库存概览</span>
              </el-menu-item>
              <el-menu-item index="/admin/inventory/warehouse" v-permission="'inventory.warehouse.view'">
                <el-icon><OfficeBuilding /></el-icon>
                <span>仓库管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/inventory/supplier" v-permission="'inventory.supplier.view'">
                <el-icon><Van /></el-icon>
                <span>供应商管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/inventory/stock-in" v-permission="'inventory.stockIn.view'">
                <el-icon><Box /></el-icon>
                <span>入库管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/inventory/stock-out" v-permission="'inventory.stockOut.view'">
                <el-icon><Sell /></el-icon>
                <span>出库管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/inventory/reports" v-permission="'inventory.view'">
                <el-icon><PieChart /></el-icon>
                <span>库存报表</span>
              </el-menu-item>
            </el-sub-menu>
          </template>
          -->
          
          <!-- 系统 - 根据功能分权限 -->
          <div class="menu-title">系统</div>
          <!-- 系统设置 - 仅管理员可见 -->
          <el-menu-item v-if="hasPermission(['admin'])" index="/admin/system-settings">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
          <!-- 数据迁移 - 仅管理员可见 -->
          <el-menu-item v-if="hasPermission(['admin'])" index="/admin/migrations">
            <el-icon><Upload /></el-icon>
            <span>数据迁移</span>
          </el-menu-item>

        </el-menu>
      </el-aside>
      <el-container>
        <el-header>
          <div class="header-left">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/admin/dashboard' }">管理后台</el-breadcrumb-item>
              <el-breadcrumb-item>{{ getPageTitle }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <el-button type="primary" size="small" @click="goToPos" class="pos-btn">
              <el-icon><ShoppingCart /></el-icon>
              <span>前往收银前台</span>
            </el-button>
            <el-dropdown trigger="click">
              <span class="user-info">
                <el-avatar size="small" icon="el-icon-user" />
                <span class="user-name">{{ userName }}</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToPos">前台收银</el-dropdown-item>
                  <el-dropdown-item @click="goToProfile">个人信息</el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <div class="content-container">
            <router-view />
          </div>
        </el-main>
        <el-footer>
          <span>© 2023 哈喽啤鲜生收银系统 - 管理后台</span>
        </el-footer>
      </el-container>
    </el-container>
    
    <!-- 个人信息弹窗 -->
    <el-dialog
      v-model="showProfileDialog"
      title="个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="profileFormRef" 
        :model="profileForm" 
        :rules="profileRules" 
        label-width="100px"
        class="profile-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="profileForm.name" />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag :type="getRoleTagType(profileForm.role)">
            {{ getRoleLabel(profileForm.role) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input v-model="profileForm.phone" />
        </el-form-item>
        
        <el-divider content-position="center">修改密码（可选）</el-divider>
        
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input 
            v-model="profileForm.oldPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password 
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="profileForm.newPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password 
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="profileForm.confirmPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleProfileCancel">取消</el-button>
          <el-button type="primary" @click="handleProfileSubmit" :loading="profileSubmitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, reactive, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/utils/api'
import { 
  Monitor, 
  Goods, 
  User, 
  Discount, 
  DataAnalysis, 
  Setting, 
  Shop, 
  Upload, 
  Folder, 
  OfficeBuilding,
  Connection,
  Document,
  ShoppingCart,
  Calendar,
  Box,
  House,
  Sell,
  Wallet,
  Van,
  PieChart,
  Share,
  PriceTag,
  Menu
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 获取页面标题
const getPageTitle = computed(() => {
  return route.meta.title ? route.meta.title.replace('管理后台 - ', '') : '概览'
})

// 当前用户角色状态
const currentUserRole = ref('cashier')

// 响应式状态
const mobileSidebarOpen = ref(false)
const isCollapsed = ref(false)
const sidebarWidth = computed(() => {
  if (isCollapsed.value) return '60px'
  return '200px'
})

// 获取当前用户信息
const getUserInfo = async () => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      currentUserRole.value = user.role || 'cashier'
      
      // 从服务器获取最新用户信息
      try {
        const response = await api.get(`/users/${user.id}`)
        if (response.data && response.data.status === 'success') {
          const updatedUser = {
            ...user,
            ...response.data.data,
            role: response.data.data.role
          }
          
          // 更新本地存储和角色状态
          localStorage.setItem('user', JSON.stringify(updatedUser))
          currentUserRole.value = updatedUser.role || 'cashier'
          
          console.log('管理后台用户信息已更新:', updatedUser, '角色:', currentUserRole.value)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }
  } catch (e) {
    console.error('解析用户信息失败', e)
  }
}

// 获取当前用户角色 - 使用响应式状态
const userRole = computed(() => currentUserRole.value)

// 检查用户是否有权限访问某个功能
const hasPermission = (requiredRoles) => {
  if (!requiredRoles || requiredRoles.length === 0) {
    return true // 未指定所需角色，所有人都可访问
  }
  
  return requiredRoles.includes(userRole.value)
}

// 用户信息
const userName = computed(() => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      return user.name || '用户'
    }
  } catch (e) {
    console.error('解析用户信息失败', e)
  }
  return '用户'
})

// 跳转到前台收银页面
const goToPos = () => {
  router.push('/')
}

// 切换移动端侧边栏
const toggleMobileSidebar = () => {
  mobileSidebarOpen.value = !mobileSidebarOpen.value
}

// 处理菜单选择事件
const handleMenuSelect = (index) => {
  // 在移动端，选择菜单项后自动关闭侧边栏
  if (window.innerWidth <= 768) {
    mobileSidebarOpen.value = false
  }
}

// 关闭移动端侧边栏
const closeMobileSidebar = () => {
  mobileSidebarOpen.value = false
}

// 监听窗口大小变化
const handleResize = () => {
  const width = window.innerWidth
  if (width <= 768) {
    isCollapsed.value = false
    mobileSidebarOpen.value = false
  } else if (width <= 1024) {
    isCollapsed.value = true
    mobileSidebarOpen.value = false
  } else {
    isCollapsed.value = false
    mobileSidebarOpen.value = false
  }
}

// 跳转到个人信息页面
const goToProfile = () => {
  showProfileDialog.value = true
}

// 个人信息弹窗显示状态
const showProfileDialog = ref(false)

// 个人信息表单
const profileForm = reactive({
  id: '',
  username: '',
  name: '',
  role: '',
  phone: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 个人信息表单验证规则
const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { 
      validator: (rule, value, callback) => {
        if (profileForm.newPassword && value !== profileForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  oldPassword: [
    { 
      validator: (rule, value, callback) => {
        if (profileForm.newPassword && !value) {
          callback(new Error('修改密码时需要输入旧密码'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 个人信息表单引用
const profileFormRef = ref(null)
const profileSubmitting = ref(false)

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    admin: 'danger',
    manager: 'warning',
    cashier: 'primary'
  }
  return types[role] || 'info'
}

// 获取角色显示名称
const getRoleLabel = (role) => {
  const labels = {
    admin: '管理员',
    manager: '经理',
    cashier: '收银员'
  }
  return labels[role] || '未知角色'
}

// 获取个人信息
const getProfileInfo = async () => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      
      // 获取最新用户信息
      const response = await api.get(`/users/${user.id}`)
      
      if (response.data && response.data.status === 'success') {
        const userData = response.data.data
        
        // 更新表单数据
        profileForm.id = userData.id
        profileForm.username = userData.username
        profileForm.name = userData.name || ''
        profileForm.role = userData.role
        profileForm.phone = userData.phone || ''
        
        // 清空密码字段
        profileForm.oldPassword = ''
        profileForm.newPassword = ''
        profileForm.confirmPassword = ''
      } else {
        ElMessage.error('获取用户信息失败: ' + (response.data?.message || '未知错误'))
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 提交个人信息表单
const handleProfileSubmit = async () => {
  if (!profileFormRef.value) return
  
  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      profileSubmitting.value = true
      
      try {
        // 准备提交数据
        const updateData = {
          name: profileForm.name,
          phone: profileForm.phone
        }
        
        // 如果填写了密码，则添加密码相关字段
        if (profileForm.newPassword) {
          updateData.oldPassword = profileForm.oldPassword
          updateData.password = profileForm.newPassword
        }
        
        // 发送更新请求
        const response = await api.put(`/users/${profileForm.id}/profile`, updateData)
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('个人信息更新成功')
          
          // 更新本地存储的用户信息
          const userStr = localStorage.getItem('user')
          if (userStr) {
            const user = JSON.parse(userStr)
            const updatedUser = {
              ...user,
              name: profileForm.name,
              phone: profileForm.phone
            }
            localStorage.setItem('user', JSON.stringify(updatedUser))
            
            // 更新显示的用户角色信息
            getUserInfo()
          }
          
          // 关闭弹窗
          showProfileDialog.value = false
        } else {
          ElMessage.error('更新失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error('更新个人信息失败:', error)
        ElMessage.error('更新个人信息失败')
      } finally {
        profileSubmitting.value = false
      }
    }
  })
}

// 关闭个人信息弹窗
const handleProfileCancel = () => {
  showProfileDialog.value = false
}

// 监听弹窗打开，获取个人信息
watch(showProfileDialog, (newVal) => {
  if (newVal) {
    getProfileInfo()
  }
})

// 处理登出
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
  }).catch(() => {})
}



// 初始应用紧凑模式设置
onMounted(() => {
  getUserInfo()



  // 初始化响应式状态
  handleResize()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  background-color: #f0f2f5;
}

.el-container {
  height: 100%;
}

.el-aside {
  background-color: #304156;
  color: #bfcbd9;
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-aside:hover {
  overflow-y: auto;
}

/* 移动端菜单按钮 */
.mobile-menu-btn {
  display: none;
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: 1500;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px;
  font-size: 18px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  background-color: #263445;
}

.logo-icon {
  margin-right: 10px;
  color: #409EFF;
}

.title {
  color: #fff;
  font-size: 16px;
  margin: 0;
}

.el-menu-vertical {
  border-right: none;
}

.el-header {
  background-color: #fff;
  color: #333;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 0 20px;
}

.header-left, .header-right {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .pos-btn {
  margin-right: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-name {
  margin-left: 8px;
  font-size: 14px;
}

.el-main {
  padding: 20px;
  background-color: #f0f2f5;
  overflow-y: auto;
}

.el-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  background-color: #f0f2f5;
  color: #909399;
  font-size: 12px;
}

.menu-divider {
  margin: 8px 0;
  height: 1px;
  background-color: rgba(255, 255, 255, 0.1);
}

.menu-title {
  color: #909399;
  font-size: 12px;
  padding: 10px 20px 5px;
  text-transform: uppercase;
}

.profile-form {
  max-width: 100%;
}

/* 响应式布局 */
@media (max-width: 1024px) and (min-width: 769px) {
  .el-aside {
    width: 60px !important;
  }

  .title {
    display: none;
  }

  .logo-container {
    padding: 10px 5px;
  }
}

@media (max-width: 768px) {
  .mobile-menu-btn {
    display: block !important;
  }

  .el-aside {
    position: fixed !important;
    left: 0;
    top: 0;
    height: 100vh;
    z-index: 2000;
    transform: translateX(-100%);
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  }

  .el-aside.mobile-open {
    transform: translateX(0);
  }

  /* 移动端遮罩层 */
  .mobile-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1999;
  }

  .el-header {
    padding-left: 50px; /* 为移动端菜单按钮留出空间 */
  }

  .el-main {
    padding: 10px;
  }

  .content-container {
    padding: 0 5px;
  }
}

@media (max-width: 480px) {
  .el-header {
    padding: 0 10px 0 50px;
    height: auto !important;
    line-height: normal !important;
    min-height: 50px;
  }

  .header-left, .header-right {
    flex-direction: column;
    align-items: flex-start;
  }

  .pos-btn {
    margin: 5px 0;
    width: 100%;
  }
}
</style> 